import django.core.files.uploadedfile
from django import forms
from django.forms.fields import FileField
from django.core.files.uploadedfile import InMemoryUploadedFile
from api import models
import uuid
class BootStrapForm(forms.ModelForm):
    exclude_class = []
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)

        for key,value in self.fields.items():
            if key in self.exclude_class:
                continue
            old_class=value.widget.attrs.get('class','')

            old_class+=' form-control'

class AuctionForm(forms.ModelForm):
    exclude_class = ['cover',]
    class Meta:
        model=models.Auction
        exclude=['status','total_price','goods_count','bid_count','look_count','video']

    def clean(self):
        clean_data=self.cleaned_data

        #获取用户提交的文件
        file_obj=clean_data.get('cover')

        #用户没有上传
        if not file_obj:
            return clean_data
        #如果编辑的时候没有修改 封面
        if isinstance(file_obj,FileField):
            return clean_data

        ext=file_obj.name.rsplit('.',maxsplit=1)[-1]
        file_name=f'{str(uuid.uuid4())}.{ext}'
        #把文件对象上传到cos 返回地址
        clean_data['cover']=file_name
        return clean_data


class AuctionItemModelForm(forms.ModelForm):
    class Meta:
        model=models.AuctionItem
        exclude=['auction','uid','bid_count','look_count','video','status','deal_price']
    def clean(self):
        clean_data=self.cleaned_data
        file_obj=self.cleaned_data.get('cover')
        if not file_obj:
            return self.clean_data
        if isinstance(file_obj,FileField):
            return self.cleaned_data
        file_name=file_obj.name.rsplit('.',maxsplit=1)[-1]
        clean_data['cover']=file_name
        return clean_data